package com.mezz.bones.im.logic.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.mezz.bones.im.common.domain.dto.ApplicationDto;
import com.mezz.bones.im.logic.service.IMessageNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MessageNotifyServiceImpl implements IMessageNotifyService {


    /**
     * 发送消息事件到 三方接入平台
     * @param applicationDto 应用信息
     * @param requestBody    请求体
     * @param sign
     * @return
     */

    @Override
    public String sendMessageNotify(ApplicationDto applicationDto, String requestBody, String sign) {
        String notifyUrl = applicationDto.getNotifyUrl();
        
        if (StrUtil.isBlank(notifyUrl)) {
            log.error("IM消息通知失败 | 请求参数:{} | 错误:{}", requestBody, "通知地址为空");
            return "";
        }

        try {

            // 发送HTTP请求
            HttpResponse response = HttpRequest.post(notifyUrl)
                    .header("Content-Type", "application/json")
                    .header("sign",sign)
                    .body(requestBody)
                    .setConnectionTimeout(5000)
                    .execute();

            // 记录请求日志
            log.debug("IM消息通知 | URL:{} | 状态码:{} | 请求体:{} | 响应体:{}",
                    notifyUrl,
                    response.getStatus(),
                    requestBody,
                    response.body());

            if (response.getStatus() != 200) {
                log.error("IM消息通知失败 | URL:{} | 状态码:{} | 请求参数:{} | 响应体:{}",
                        notifyUrl,
                        response.getStatus(),
                        requestBody,
                        response.body());
                return "";
            }

            return response.body();

        } catch (Exception e) {
            log.error("IM消息通知异常 | URL:{} | 错误:{}", notifyUrl, e.getMessage(), e);
        }

        return "";
    }


    /**
     * 生成通知接口签名
     */
    @Override
    public String generateNotifySign(String appSecret, String body) {
        String plaintext = StrUtil.concat(true, appSecret,body);
        String sign = SecureUtil.sha256(plaintext);
        log.debug("IM通知签名生成 | 明文:{} | 签名:{}", plaintext, sign);
        return sign;
    }
}